package com.zz.yt.lib.login.delegate.login.base;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.whf.android.jar.app.Latte;
import com.whf.android.jar.net.RestClient;
import com.whf.android.jar.util.log.LatteLogger;
import com.zz.yt.lib.login.grade.UpDateUtils;
import com.zz.yt.lib.login.grade.bean.GradeBean;

import org.jetbrains.annotations.NotNull;

import java.util.List;


/**
 * 默认可以获得的值
 *
 * @author qf
 * @version 1.0
 **/
abstract class BaseGradeDelegate extends BaseDataDelegate {

    /**
     * 更新权限回调key
     */
    int REQUEST_CODE = 1255;


    /**
     * 更新内容
     */
    protected GradeBean mGradeBean = null;

    /**
     * 获得更新权限
     */
    protected void inGradePermission() {
        upGradeNet();
        onGrantedSuccess();
    }

    /**
     * 查询升级
     */
    private void upGradeNet() {
        if (Latte.getDebug()) {
            //debug 不需要更新
            setGranted(false);
            return;
        }
        RestClient.builder()
                .url( Latte.getCheckVersionServer())
                .params("appId", Latte.getAppId())
                .params("versionCode", Latte.getVersionCode())
                .analysis(true)
                .success(response -> {
                    mGradeBean = GsonUtils.fromJson(response, GradeBean.class);
                    final boolean needUpdate = mGradeBean.isNeedUpdate();
                    setGranted(needUpdate);
                    if (needUpdate) {
                        storagePermission();
                    } else {
                        onGrantedSuccess();
                        LatteLogger.i("不需要更新");
                    }
                })
                .build()
                .get();
    }

    /**
     * 获得更新de存储权限
     */
    private void storagePermission() {
        PermissionUtils
                .permission(PermissionConstants.STORAGE)
                .rationale((activity, shouldRequest) -> shouldRequest.again(true))
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(@NotNull List<String> permissionsGranted) {
                        LatteLogger.d("权限获取成功", permissionsGranted);
                        setStoragePermission();
                    }

                    @Override
                    public void onDenied(@NotNull List<String> permissionsDeniedForever, @NotNull List<String> permissionsDenied) {
                        LatteLogger.d("权限永久拒绝", permissionsDeniedForever);
                        LatteLogger.d("权限拒绝", permissionsDenied);
                        if (getProxyActivity() != null) {
                            getProxyActivity().finish();
                        }
                    }
                })
                .theme(ScreenUtils::setFullScreen)
                .request();
    }

    /**
     * 获得Android R 的更新权限以上设置特殊权限（存储）
     */
    private void setStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            LatteLogger.i("先判断有没有R以上的特殊存储权限");
            if (Environment.isExternalStorageManager()) {
                upDataNet();
            } else {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + context.getPackageName()));
                startActivityForResult(intent, REQUEST_CODE);
            }
        } else {
            upDataNet();
        }
    }

    /**
     * 更新，及设置点击事件
     */
    private void upDataNet() {
        setInstallPermission();
    }

    /**
     * 8.0以上系统设置危险权限（安装未知来源权限）
     */
    @Override
    protected void installApk() {
        super.installApk();
        showPopup();
    }


    /**
     * 成功获取安装权限，弹出需要更新和更新内容提示框
     */
    protected void showPopup() {
        UpDateUtils.create()
                .setDate(mGradeBean)
                .setOnClickListener(v -> {
                    if (getProxyActivity() != null) {
                        getProxyActivity().finish();
                    }
                })
                .show();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                upDataNet();
            } else {
                ToastUtils.showShort("存储权限获取失败");
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if (ActivityCompat.checkSelfPermission(Latte.getActivity(),
                    Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(Latte.getActivity(),
                            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                upDataNet();
            } else {
                ToastUtils.showShort("存储权限获取失败");
            }
        }
    }

    /**
     * 无需更新的其他操作
     */
    protected abstract void onGrantedSuccess();


}
